/*
 * Created on Feb 14, 2005
 * Created by dfhuynh
 */
package edu.mit.simile.longwell.ui;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.app.VelocityEngine;

import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.LongwellServlet;
import edu.mit.simile.longwell.Profile;
import edu.mit.simile.longwell.query.Query;

/**
 * @author dfhuynh
 */
public class FlairMessage {
	final public LongwellServlet			m_servlet;
	final public HttpServletRequest		m_request;
	final public HttpServletResponse 	m_response;

	final public VelocityEngine			m_ve;

	final public String		m_profileID;
	final public Query		m_query;
	final public String		m_locale;

	public FlairMessage(
			LongwellServlet		servlet,
			HttpServletRequest	request,
			HttpServletResponse	response,
			VelocityEngine		ve,
			String				profileID,
			Query 				query,
			String				locale
			) {
		m_servlet = servlet;

		m_request = request;
		m_response = response;
		m_ve = ve;

		m_profileID = profileID;
		m_query = query;
		m_locale = locale;
	}

	public Profile getProfile() {
		return LongwellServer.getServer().getProfile(m_request.getSession().getId());
	}
	public Profile getProfile(String id) {
		return LongwellServer.getServer().getProfile(id);
	}
	public Profile getProfileFromSession(){
		return  LongwellServer.getServer().getProfile(m_request.getSession().getId());
	}

	public Query getQuery() {
		return m_query;
	}
	public void removeProfile(String sessionId){
		LongwellServer.getServer().removeProfile(sessionId);
	}

	public String getURL(RDFNode node) {
		String s;
		if (node instanceof Resource) {
			Resource r = (Resource) node;
			Profile profile = getProfile();

			if (profile.getModel().contains(r, RDF.type)) {
				String pseudoURI = profile.getSchemaModel().resourceToPseudoURI(r);
				FlairURL flairURL = new FlairURL(this).changeCommandQuery(
					"focus", "pseudoURI=" + URLEncoder.encode(pseudoURI));

				return flairURL.toURLString();
			} else if (r.isAnon()) {
				return "";
			}
			s = r.getURI();
		} else {
			s = ((Literal) node).getString();
		}

		try {
			URL url = new URL(s);

			return url.toExternalForm();
		} catch (MalformedURLException e) {
			return "";
		}
	}
}
